package com.hanshg.cherry.service.impl.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.hanshg.cherry.config.scheduler.CronTaskRegistrar;
import com.hanshg.cherry.config.scheduler.SchedulingRunnable;
import com.hanshg.cherry.model.SysJob;
import com.hanshg.cherry.service.job.JobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName SysJobRunner
 * @Description 实现了CommandLineRunner接口的SysJobRunner类，当spring boot项目启动完成后，加载数据库里状态为正常的定时任务
 * @Author 柠檬水
 * @Date 2020/4/20 11:45
 * @Version 1.0
 **/
@Service
@Slf4j
public class SysJobRunner implements CommandLineRunner {

    private final JobService jobService;

    private final CronTaskRegistrar cronTaskRegistrar;

    public SysJobRunner(JobService jobService, CronTaskRegistrar cronTaskRegistrar) {
        this.jobService = jobService;
        this.cronTaskRegistrar = cronTaskRegistrar;
    }

    /**
     * 运行
     *
     * @param args arg游戏
     */
    @Override
    public void run(String... args) {
        log.info("系统定时任务开始加载........");
        // 初始加载数据库里状态为正常的定时任务
        QueryWrapper<SysJob> wrapper = new QueryWrapper();
        wrapper.eq("status",SysJob.Status.NORMAL);
        List<SysJob> jobList = jobService.list(wrapper);
        if (CollectionUtils.isNotEmpty(jobList)) {
            for (SysJob job : jobList) {
                SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParam());
                cronTaskRegistrar.addCronTask(task, job.getCron());
            }
        }
        log.info("定时任务已加载完毕..."+jobList.size());
    }
}
